import { useMainStore } from "@/stores/main";
import { Link,LoginCredentials, SortIndexUpdate,Config } from "./types";

const apiBase = import.meta.env.VITE_API_BASE

// ApiError 类定义
class ApiError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
    this.name = 'ApiError';
  }
}

// API 请求工具函数
async function apiFetch(endpoint, options = {}) {
  const store = useMainStore();
  const token = store.token;

  const headers = {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: token } : {}),
    ...options.headers
  };

  console.log('Sending request with token:', token);
  const response = await fetch(`${apiBase}${endpoint}`, {
    ...options,
    headers
  });

  // 处理 401 未授权状态
  if (response.status === 401) {
    store.logout();
    throw new ApiError(401, 'Unauthorized');
  }

  // 处理错误响应
  if (!response.ok) {
    throw new ApiError(response.status, `HTTP error! status: ${response.status}`);
  }

  // 处理响应数据
  const responseHeaders = response.headers;
  let data;
  const contentType = responseHeaders.get('content-type');
  if (contentType?.includes('application/json')) {
    data = await response.json();
  } else {
    data = {};
  }

  return { data, headers: responseHeaders };
}

// API 接口对象
const api = {
  // 登录接口
  async login(credentials) {
    const { headers } = await apiFetch('/login', {
      method: 'POST',
      body: JSON.stringify(credentials)
    });

    // 从响应头获取 token
    const token = headers.get('Authorization');
    if (!token) {
      throw new Error('No token received');
    }

    return token;
  },

  // 获取导航链接
  async getNavigation() {
    const { data } = await apiFetch('/navigation');
    return data;
  },

  // 获取最后修改时间
  async getLastModified() {
    const { data } = await apiFetch('/navigation/last-modified');
    return data;
  },

  // 添加链接
  async addLink(link) {
    await apiFetch('/navigation/add', {
      method: 'POST',
      body: JSON.stringify(link)
    });
  },

  // 更新链接
  async updateLink(index, link) {
    await apiFetch(`/navigation/update/${index}`, {
      method: 'PUT',
      body: JSON.stringify(link)
    });
  },

  // 删除链接
  async deleteLink(index) {
    await apiFetch(`/navigation/delete/${index}`, {
      method: 'DELETE'
    });
  },

  // 获取网站图标
  async getWebsiteIcon(url) {
    const { data } = await apiFetch(`/get-icon?url=${encodeURIComponent(url)}`);
    return data.iconData;
  },

  // 更新排序索引
  async updateSortIndices(updates) {
    await apiFetch('/navigation/sort', {
      method: 'PUT',
      body: JSON.stringify({ updates })
    });
  },

  // 更新分类
  async updateCategories(categories) {
    await apiFetch('/navigation/categories', {
      method: 'PUT',
      body: JSON.stringify({ categories })
    });
  },

  // 获取配置
  async getConfig() {
    const { data } = await apiFetch('/config');
    return data;
  },

  // 验证令牌
  async validateToken() {
    const { data } = await apiFetch('/validate');
    return data;
  }
};

export {
  api,
  ApiError
};